<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期" prop="date" label-width="50px">
        <el-date-picker
          clearable
          v-model="queryParams.date"
          type="date"
          value-format="yyyy-MM-dd"
          @change="handleQuery"
          placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
<!--      <el-form-item label="车次" prop="order">-->
<!--        <el-input-->
<!--          v-model="queryParams.order"-->
<!--          placeholder="请输入车次"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--          @change="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="车号" prop="number" label-width="50px">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入车号"
          clearable
          @keyup.enter.native="handleQuery"
          @change="handleQuery"
        />
      </el-form-item>

      <el-form-item label="故障详情" prop="detail">
        <el-input
          v-model="queryParams.detail"
          placeholder="请输入故障详情"
          clearable
          @change="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="responsibleTeam" label-width="50px">
        <el-select v-model="status" placeholder="请选择"  @change="queryFault" clearable>
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
<!--      <el-form-item label="处理人" prop="processor">-->
<!--        <el-input-->
<!--          v-model="queryParams.processor"-->
<!--          placeholder="请输入处理人"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="故障推送时间" prop="pushTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.pushTime"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择故障推送时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:summary:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-upload ref="plante"
                   :file-list="plantefileList"
                   :action="planteAction"
                   :headers="headers"
                   :before-upload="planteBeforeUpload"
                   :on-success="uploadExcelSuccess"
                   accept=".xls,.xlsx">
          <el-button size="small" type="primary" icon="el-icon-upload">故障上传</el-button>
          <!--          <div slot="tip" class="el-upload__tip">只能上传不超过 5MB 的.xls,.xlsx文件</div>-->
        </el-upload>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:summary:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:summary:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:summary:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" ref="table"
              :data="summaryList"
              stripe
              @selection-change="handleSelectionChange"
              :cell-style="columnStyle"
              @sort-change="onSortChange"
              @filter-change="filterHandler">
      <el-table-column type="selection" width="55" align="center"  />
<!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="日期" align="center" prop="date"  sortable="custom" :sort-orders="['ascending', 'descending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车次" align="center" prop="orders" sortable="custom" :sort-orders="['ascending', 'descending']"/>
      <el-table-column label="车号" align="center" prop="number" sortable="custom" :sort-orders="['ascending', 'descending']" />
      <el-table-column label="故障详情" align="center" prop="detail" />
      <el-table-column label="flag" v-if="queryParams.isRepeat === '1'" align="center" prop="flag" />
      <el-table-column label="parentFlag" v-if="queryParams.isRepeat === '1'" align="center" prop="parentFlag" />
      <el-table-column label="key" align="center" width="200" prop="key" />
      <el-table-column label="提交人" v-if="queryParams.isRepeat !== '1'" align="center" prop="submitter" />
      <el-table-column label="责任班组" v-if="queryParams.isRepeat !== '1'" align="center" prop="responsibleTeam" />
      <el-table-column label="处理人" v-if="queryParams.isRepeat !== '1'" align="center" prop="processor" />
      <el-table-column label="处理结果" v-if="queryParams.isRepeat !== '1'" align="center" prop="result" />
      <el-table-column label="故障推送时间" v-if="queryParams.isRepeat !== '1'" align="center" prop="pushTime" width="150" sortable="custom" :sort-orders="['ascending', 'descending']">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pushTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
        <el-table-column label="上传时间" v-if="queryParams.isRepeat !== '1'" align="center" prop="createTime" width="150" sortable="custom"
                         :sort-orders="['ascending', 'descending']"
                         :filters="uploadTime"
                         column-key="tag">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="故障条数" v-if="queryParams.isRepeat === '1'" align="center" prop="finFlagNum" />
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
<!--          <el-tag v-if="scope.row.isFail === 1" type="success">匹配成功</el-tag>-->
          <el-tag v-if="scope.row.isRepeat === 1" size="mini" type="danger">重复故障</el-tag>
          <el-tag v-if="scope.row.isParent === 1" size="mini" type="warning">父辈</el-tag>
<!--          <el-tag v-if="scope.row.isFail === 0" size="mini" type="warning">匹配失败</el-tag>-->
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['system:summary:edit']"-->
<!--          >修改</el-button>-->
           <el-button
             v-if="queryParams.isRepeat === '1'"
            size="mini"
            type="text"
            icon="el-icon-chat-line-square"
            @click="handleDetail(scope.row)"
            v-hasPermi="['system:summary:edit']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:summary:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 重复故障 -->
    <el-dialog :title="title"
               :visible.sync="detailOpen"
               append-to-body
               center
               width="70%"
               show-close>
      <h3 style="float: right">故障总数:{{faultNum}}</h3>
      <el-table v-loading="loading" ref="table"
                :data="repeatList"
                stripe
                @selection-change="handleSelectionChange"
                :cell-style="columnStyle"
                @sort-change="onSortChange"
                @filter-change="filterHandler">
<!--        <el-table-column type="selection" width="55" align="center"  />-->
<!--              <el-table-column label="id" align="center" prop="id" />-->
        <el-table-column label="日期" align="center" prop="date"  sortable="custom" :sort-orders="['ascending', 'descending']">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="车次" align="center" prop="orders" sortable="custom" :sort-orders="['ascending', 'descending']"/>
        <el-table-column label="车号" align="center" prop="number" sortable="custom" :sort-orders="['ascending', 'descending']" />
        <el-table-column label="故障详情" align="center" prop="detail" min-width="150px" />
        <el-table-column label="flag" align="center" prop="flag" />
        <el-table-column label="parentFlag" align="center" prop="parentFlag" />
        <el-table-column label="key" align="center" width="200" prop="key" />
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <!--          <el-tag v-if="scope.row.isFail === 1" type="success">匹配成功</el-tag>-->
            <el-tag v-if="scope.row.isRepeat === 1" size="mini" type="danger">重复故障</el-tag>
            <el-tag v-if="scope.row.isParent === 1" size="mini" type="warning">父辈</el-tag>
            <!--          <el-tag v-if="scope.row.isFail === 0" size="mini" type="warning">匹配失败</el-tag>-->
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleRemove(scope.row)"
              v-hasPermi="['system:summary:remove']"
            >去除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-dialog>


    <!-- 添加或修改故障总表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="日期" prop="date">
          <el-date-picker clearable
            v-model="form.date"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="车次" prop="orders">
          <el-input v-model="form.orders" placeholder="请输入车次" />
        </el-form-item>
        <el-form-item label="车号" prop="number">
          <el-input v-model="form.number" placeholder="请输入车号" />
        </el-form-item>
        <el-form-item label="故障详情" prop="detail">
          <el-input v-model="form.detail" placeholder="请输入故障详情" />
        </el-form-item>
        <el-form-item label="提交人" prop="submitter">
          <el-input v-model="form.submitter" placeholder="请输入提交人" />
        </el-form-item>
        <el-form-item label="责任班组" prop="responsibleTeam">
          <el-input v-model="form.responsibleTeam" placeholder="请输入责任班组" />
        </el-form-item>
        <el-form-item label="处理人" prop="processor">
          <el-input v-model="form.processor" placeholder="请输入处理人" />
        </el-form-item>
        <el-form-item label="处理结果" prop="result">
          <el-input v-model="form.result" placeholder="请输入处理结果" />
        </el-form-item>
        <el-form-item label="推送时间" prop="pushTime">
          <el-date-picker clearable
            v-model="form.pushTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择故障推送时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSummary,
  getSummary,
  delSummary,
  addSummary,
  updateSummary,
  findUniqueDates,
  selectListByFlag, removeSummary
} from "@/api/system/summary";
import {getToken} from "@/utils/auth";
import {getDaysBetweenDates} from "@/utils/dateFormYMD";

export default {
  name: "Summary",
  data() {
    return {
      faultNum:0,
      status:null,
      uploadTime:[],
      options: [{
        value: '1',
        label: '重复故障'
      },{
        value: '待料',
        label: '待料'
      }],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 故障总表表格数据
      summaryList: [],
      repeatList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        date: null,
        order: null,
        number: null,
        detail: null,
        submitter: null,
        responsibleTeam: null,
        processor: null,
        result: null,
        pushTime: null,
        createTime:null,
        timeGroup:null,
        isRepeat: null,
        isParent: null,
        // 排序的列表字段
        orderByColumn: null,
        // asc正序 desc倒序
        isAsc: null
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        date: [{ required: true, message: "日期不能为空", trigger: "blur" }],
        orders: [{ required: true, message: "车次为空", trigger: "blur" }],
        number: [{ required: true, message: "车号不能为空", trigger: "blur" }],
        detail: [{ required: true, message: "故障不能为空", trigger: "blur" }],
      },
      planteAction: process.env.VUE_APP_BASE_API+'/system/excel/uploadSummary/',
      plantefileList: [],
    };
  },
  computed: {
    headers() {
      const authorization = getToken() || ''
      return { authorization }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    queryFault(){
      this.queryParams.isRepeat = null
      this.queryParams.isParent = null
      this.queryParams.result = null
      if (this.status === '待料'){
        this.queryParams.result = this.status
      }else if (this.status === '1'){
        //重复故障
        this.queryParams.isRepeat = this.status
        this.queryParams.isParent = this.status
      }
      this.queryParams.orderByColumn = 'number'
      this.queryParams.isAsc = 'desc'
      this.getList()
      // this.reset();
    },
    findAllUniqueDates(){
      this.uploadTime = []
      findUniqueDates().then(response => {
        for (let i=0;i<response.length;i++){

          this.uploadTime.push({
            value:response[i],
            text:response[i]
          })
        }
      });
    },
    resetFilter() {
      this.$refs.table.clearFilter('createTime');
    },
    clearFilter() {
      this.$refs.table.clearFilter();
    },
    filterHandler(value) {
      this.queryParams.timeGroup = JSON.stringify(value)
      console.log(this.queryParams.timeGroup)
      this.getList()
    },
    // 点击排序
    onSortChange(column) {
      this.queryParams.orderByColumn = column.prop
      this.queryParams.isAsc = column.order === "ascending" ? 'asc' : 'desc'
      // 获取后台列表数据
      this.getList()
    },

    disabledDate(time) {
      // 获取今天的日期
      const today = new Date();
        // 如果选择的日期在今天之后，则禁用
      return time.getTime() > today.getTime();
    },
    //是否重复故障，显色
    columnStyle({ row, rowIndex }) {
      let currentTime = new Date()
      let pushTime = new Date(row.pushTime)
      let day = getDaysBetweenDates(pushTime,currentTime)
      // console.log(day)
      //大于3小于7天显示黄色
      // if(row.isFail){
      //   return 'background:rgba(255,255,0,.1);';
      // }
      //大于0小于3天显示红色
      if(row.isRepeat === 1){
        return 'background:rgba(255,0,0,.1);'
      }else if(row.isParent === 1){
        return 'background:rgba(255,255,0,.1);'
      }
      else if(rowIndex % 2 === 0){
        return 'background:white;'
      }else if (rowIndex % 2 ===1){
        return 'background:#FAFAFA;'
      }
      // if(day > 3  && day <= 7){
      //   return 'background:rgba(255,255,0,.1);';
      // }
      // //大于0小于3天显示红色
      // if(day >= 0 && day <= 3){
      //   return 'background:rgba(255,0,0,.1);'
      // }
    },
    planteBeforeUpload(file) {
      let isRightSize = file.size / 1024 / 1024 < 50
      if (!isRightSize) {
        this.$message.error('文件大小超过 50MB')
      }
      let isAccept = new RegExp('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet|application/vnd.ms-excel').test(file.type)
      if (!isAccept) {
        this.$message.error('应该选择.xls,.xlsx类型的文件')
      }
      return isRightSize && isAccept
    },
    uploadExcelSuccess(response){
      if (response.code === 200){
        this.$message.success(response.msg)
      }else {
        this.$message.error("上传失败,请检查表格数据!")
      }

      this.$refs.plante.clearFiles();
      this.getList();
      this.reset();
    },
    /** 查询故障总表列表 */
    getList() {
      this.findAllUniqueDates();
      // console.log("getList")
      this.loading = true;
      this.summaryList = []
      listSummary(this.queryParams).then(response => {
        this.summaryList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.summaryList = list
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    detailCancel() {
      this.detailOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        date: null,
        orders: null,
        number: null,
        detail: null,
        submitter: null,
        responsibleTeam: null,
        processor: null,
        result: null,
        pushTime: null,
        createTime:null,
        timeGroup:null,
        isFail:null,
        isRepeat:null,
        isParent: null,
        repeatNum:null,
        status:null,
        plantefileList:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.orderByColumn = null
      this.queryParams.isAsc = null
      this.$refs.table.clearSort()
      this.queryParams.pageNum = 1
      this.queryParams.isRepeat = null
      this.queryParams.isParent = null
      this.queryParams.createTime = null
      this.queryParams.timeGroup = null
      this.status = null
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加故障总表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSummary(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改故障总表";
      });
    },
    /** 故障详情按钮操作 */
    handleDetail(row) {
      let parentKey = null
      if(row.isParent === 1){
        parentKey = row.parentFlag
      }
      this.repeatList = []
      this.reset();
      selectListByFlag(row.finFlag,row.number).then(response => {
        this.repeatList = response;
        this.faultNum = response.length
        this.detailOpen = true;
        this.title = "重复故障";
      });
    },
    /** 去除故障按钮操作 */
    handleRemove(row) {
      this.$modal.confirm('是否确认去除所选数据？').then(function() {
        return removeSummary(row.id);
      }).then(() => {
        let i
        for (i=0;i<this.repeatList.length;i++){
          if (this.repeatList[i].id === row.id){
            break;
          }
        }
        this.repeatList = this.repeatList.filter(item => item.id !== row.id);
        this.faultNum = this.repeatList.length
        if (this.faultNum === 0){
          this.queryFault()
          this.detailOpen = false
        }
        // this.handleDetail(row)
        this.$modal.msgSuccess("去除成功");
      }).catch(() => {});

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSummary(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSummary(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除所选数据？').then(function() {
        return delSummary(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/summary/export', {
        ...this.queryParams
      }, `summary_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
